﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

/// <summary>
/// Summary description for RoleDAL
/// </summary>
public class RoleDAL
{
    SqlConnection connection;
    SqlCommand cmd;

	public RoleDAL()
	{
        try
        {
            /*initilaize db variables*/
            connection = new SqlConnection(
                ConfigurationManager.ConnectionStrings["loanConnectionString"].ConnectionString);
            cmd = new SqlCommand("", connection);
        }
        catch
        {
            throw new Exception("Unable to connect to database");
        }
	}

    public DataResponse<List<Role>> GetAllRoles()
    {
        DataResponse<List<Role>> response = new DataResponse<List<Role>>();

        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "GetAllRoles";

        try
        {
            cmd.Connection.Open();

            using (SqlDataReader dataReader = cmd.ExecuteReader())
            {
                if (dataReader != null)
                {
                    if (dataReader.HasRows)
                    {
                        List<Role> roles = new List<Role>();

                        while (dataReader.Read())
                        {
                            Role role = new Role();

                            if (!dataReader.IsDBNull(dataReader.GetOrdinal("role_id")))
                            {
                                role.RoleID = Convert.ToInt64(dataReader["role_id"]);

                                if (!dataReader.IsDBNull(dataReader.GetOrdinal("name")))
                                {
                                    role.Name = Convert.ToString(dataReader["name"]);
                                }
                                if (!dataReader.IsDBNull(dataReader.GetOrdinal("description")))
                                {
                                    role.Description = Convert.ToString(dataReader["description"]);
                                }
                            }

                            roles.Add(role);
                        }

                        response.Result = roles;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (cmd.Connection.State != ConnectionState.Closed)
                cmd.Connection.Close();
        }

        return response;
    }
}